//
//  CLAudioControlPanel.swift
//  clreader
//
//  Created by colin on 2019/4/3.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import SnapKit

class CLAudioControlPanel: UIView {

    /// 高度
    let containerHeight:CGFloat = 44.0
    
    /// 距离底部, 正整数，不要用负数
    var bottom:CGFloat = 0 {
        didSet {
            self.bottomConstraint?.constraint.update(offset: -self.bottom)
        }
    }
    
    private lazy var buttonStop = UIButton(type: .custom)
    private lazy var buttonPre = UIButton(type: .custom)
    private lazy var buttonPlay = UIButton(type: .custom)
    private lazy var buttonNext = UIButton(type: .custom)
    
    private lazy var labelTitle = UILabel()
    
    private var bottomConstraint:ConstraintMakerEditable?
    
    private var playerStatusDispose:Disposable?
    private var playerAudioChangedDispose:Disposable?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(hex: "000000", alpha: 0.5)
        self.layer.cornerRadius = self.containerHeight / 2
        self.layer.masksToBounds = true
        
        self.buttonPlay.addTarget(self, action: #selector(self.actionPlay(_:)), for: .touchUpInside)
        self.buttonPre.addTarget(self, action: #selector(self.actionPre(_:)), for: .touchUpInside)
        self.buttonNext.addTarget(self, action: #selector(self.actionNext(_:)), for: .touchUpInside)
        self.buttonStop.addTarget(self, action: #selector(self.actionStop(_:)), for: .touchUpInside)

        self.buttonStop.setImage(UIImage(named: "voice_close"), for: .normal)
        self.buttonPre.setImage(UIImage(named: "voice_last"), for: .normal)
        self.buttonPlay.setImage(UIImage(named: "voice_play"), for: .normal)
        self.buttonNext.setImage(UIImage(named: "voice_next"), for: .normal)
        
        self.addSubview(self.buttonStop)
        self.buttonStop.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15.0)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(self.snp.height)
        }
        
        self.addSubview(self.buttonNext)
        self.buttonNext.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-15.0)
            make.width.equalTo(self.snp.height)
        }
        
        self.addSubview(self.buttonPlay)
        self.buttonPlay.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalTo(self.buttonNext.snp.left)
            make.width.equalTo(self.snp.height)
        }
        
        self.addSubview(self.buttonPre)
        self.buttonPre.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalTo(self.buttonPlay.snp.left)
            make.width.equalTo(self.snp.height)
        }
        
        self.labelTitle.do {
            $0.text = "音频标题"
            $0.textColor = UIColor.white
            $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
        }
        self.addSubview(self.labelTitle)
        self.labelTitle.snp.makeConstraints { (make) in
            make.left.equalTo(self.buttonStop.snp.right)
            make.centerY.equalToSuperview()
            make.right.equalTo(self.buttonPre.snp.left)
        }
    }
    
    func show() {
        if let rootView = UIApplication.shared.keyWindow?.rootViewController?.view {
            rootView.addSubview(self)
            self.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(25.0)
                make.right.equalToSuperview().offset(-25.0)
                make.height.equalTo(self.containerHeight)
                self.bottomConstraint = make.bottom.equalTo(rootView.safeAreaLayoutGuide.snp.bottom).offset(-66.0)
            }
            rootView.bringSubviewToFront(self)
        }

        let player = CLAudioPlayer.shared
        
        self.playerStatusDispose = player.status.observe { [weak self] (new, old) in
            // 播放按钮状态
            if new == .playing {
                self?.buttonPlay.setImage(UIImage(named: "voice_pause"), for: .normal)
            } else {
                self?.buttonPlay.setImage(UIImage(named: "voice_play"), for: .normal)
            }
            
            // 正在加载
            if new == .loading {
                
            }
        }
        
        self.playerAudioChangedDispose = player.current.observe { [weak self] (new, old) in
            self?.labelTitle.text = new?.title
            // 检查上一个下一个按钮
            self?.buttonPre.isEnabled = CLAudioPlayer.shared.hasPre
            self?.buttonNext.isEnabled = CLAudioPlayer.shared.hasNext
        }
        
        // 初始化状态
        if player.status.value == .playing {
            self.buttonPlay.setImage(UIImage(named: "voice_pause"), for: .normal)
        } else {
            self.buttonPlay.setImage(UIImage(named: "voice_play"), for: .normal)
        }
        self.labelTitle.text = player.current.value?.title
        // 检查上一个下一个按钮
        self.buttonPre.isEnabled = player.hasPre
        self.buttonNext.isEnabled = player.hasNext
        
    }
    
    func reload() {
        self.isHidden = !self.isNeedShow
    }
    
    /// 是否需要显示
    private var isNeedShow:Bool {
        // 先判断是否需要显示,需要显示就纠正位置
        let player = CLAudioPlayer.shared
        var isNeedShow = true
        
        if let topViewController = self.topViewController() {
            switch topViewController {
            // 不需要显示controller
            case is HomeViewController,
                 is DiscoveryViewController,
                 is BuyedViewController,
                 is MyViewController,
                 is AudioPlayViewController:
                isNeedShow = false
            default:
                let status = player.status.value
                if status != .stopped && status != .ended && status != .error {
                    isNeedShow = true
                } else {
                    isNeedShow = false
                }
            }
        } else {
            isNeedShow = false
        }
        
        return isNeedShow
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension CLAudioControlPanel {
    
    @objc private func actionPlay(_ sender:Any) {
        
        let player = CLAudioPlayer.shared
        let status = player.status.value
        if status == .paused || status == .ended {
            player.startOrResume()
        } else if status == .playing {
            player.pause()
        } else {
            // 其他状态，不作任何操作
        }
    }
    
    @objc private func actionPre(_ sender:Any) {
        let player = CLAudioPlayer.shared
        player.playPre()
    }
    
    @objc private func actionNext(_ sender:Any) {
        let player = CLAudioPlayer.shared
        player.playNext()
    }
    
    @objc private func actionStop(_ sender:Any) {
        let player = CLAudioPlayer.shared
        player.stop()
    }
}

extension CLAudioControlPanel {
    
    private func topViewController() -> UIViewController? {
        // app默认windowLevel是UIWindowLevelNormal，如果不是，找到它
        guard let window = UIApplication.shared.windows.first(where: { (item) -> Bool in
            return item.windowLevel == .normal
        }) else {
            print("keywindow not found")
            return nil
        }
        
        // 找到rootviewcontroller
        guard let rootViewController = window.rootViewController else {
            print("keywindow has no rootviewcontroller")
            return nil
        }

        var topViewController = rootViewController
        
        while true {
            if let controller = topViewController.presentedViewController {
                topViewController = controller
            } else if let navController = topViewController as? UINavigationController, let controller = navController.topViewController {
                topViewController = controller
            } else if let tabBarController = topViewController as? UITabBarController, let controller = tabBarController.selectedViewController {
                topViewController = controller
            } else {
                break
            }
        }
        
        return topViewController
        
    }

}
